/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2023. All rights reserved.
 *
 */

import path from 'path';

import fse from 'fs-extra';

import { SignTypeEnum } from '../enum/sign-type-enum.js';
import { OhosLogger } from '../utils/log/ohos-logger.js';
import { TaskNames } from './common/task-names.js';
import { PackageHqf } from './package-hqf.js';
import { Quickfix } from './prepare-quickfix.js';
import { TargetTaskService } from './service/target-task-service.js';
import { SignModel } from './sign/command-builder-impl/sign-model.js';
import { getHqfName, SignUtil } from './sign/sign-util.js';
import { OhosHapTask } from './task/ohos-hap-task.js';

const logger = OhosLogger.getLogger('SignHqf');

export class SignHqf extends OhosHapTask {
  constructor(taskService: TargetTaskService) {
    super(taskService, TaskNames.Task.SIGN_HQF);
  }

  protected async doTaskAction() {
    const unsignedHqf = path.resolve(this.pathInfo.getModuleBuildOutputPath(), getHqfName(this.moduleName, this.targetName, false));
    const signedHqfName = getHqfName(this.moduleName, this.targetName, true);
    const signedHqf = path.resolve(this.pathInfo.getModuleBuildOutputPath(), signedHqfName);
    const signModel = new SignModel(SignTypeEnum.HQF, unsignedHqf, signedHqf);
    const signUtil = new SignUtil(this.service, SignTypeEnum.HQF, this.pathInfo, this.targetData.getProduct(), this.sdkInfo);
    await signUtil.sign(signModel, this.durationEvent);
    if (signUtil._signingConfig) {
      await this.updateQuickfixLog(signedHqfName);
    }
  }

  initTaskDepends(): void {
    this.declareDepends(PackageHqf.name);
  }

  private async updateQuickfixLog(signedHqfName: string) {
    const file: string = path.resolve(this.pathInfo.getModuleBuildOutputPath(), 'quickfix.json');
    if (!fse.existsSync(file)) {
      return;
    }
    const quickfixLog: Quickfix = await fse.readJSON(file, { encoding: 'utf-8' });
    quickfixLog.file = signedHqfName;
    await fse.writeJSON(file, quickfixLog);
  }

  /**
   * 用于根据buildConfig文件里的mode判断重载类型
   * 值：hotReload coldReload
   */
  getPatchConfigMode() {
    const buildConfigPath = this.pathInfo.getBuildConfigPath();
    if (fse.existsSync(buildConfigPath)) {
      const buildConfig = fse.readJsonSync(buildConfigPath);
      return buildConfig?.patchConfig?.mode;
    } else {
      logger.error(`${buildConfigPath} is not exists`);
    }
  }
}
